package maldade.persistence.configuration;

import java.io.File;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class PersistenceConfiguration
{
	private static final Log log = LogFactory.getLog(PersistenceConfiguration.class);
	
	private static SessionFactory sessionFactory;
	
	/**
	 * Static.
	 */
	private PersistenceConfiguration()
	{
		
	}
	
	/**
	 * Loads a configuration file.
	 * 
	 * @param configurationPath
	 */
	public static void configure(String configurationPath)
	{
		//Try to load the properties
		
		File file = new File(configurationPath);
    	
    	if(!file.exists() || file.isDirectory())
    	{
    		String msg = "Hibernate configuration file was not found: " + configurationPath;
    	
    		log.error(msg);
    		
    		throw new RuntimeException(msg);
    	}
    	
    	//Try to load hibernate configuration
    	
    	try {
			Configuration hibernateConfiguration = new Configuration();
			
			File hibernateFile = new File(configurationPath);
			
			hibernateConfiguration.configure(hibernateFile.toURI().toURL());

            sessionFactory = hibernateConfiguration.buildSessionFactory();
        }
        catch ( Throwable t ) {
        	
            log.error( "Could not configure hibernate", t );
            
            throw new RuntimeException( t );
        }
	}

	/**
	 * Returns the session factory.
	 * 
	 * @return SessionFactory
	 */
	public static SessionFactory getSessionFactory()
	{
		return sessionFactory;
	}
}
